import React, { useState, useEffect } from 'react';
import { message, Select } from 'antd';
import { TjModal } from '../TjModal';
import SelectMarketingUnit from './SelectMarketingUnit';
import { TjModalTitle } from '../TjModal/TjModalTitle';
import type { DataNode } from 'antd/lib/tree';
import type { Key } from 'react';
import _ from 'lodash';
import './index.less';
import { getAllMarketingUnit } from './utils';

/**
 *  交易单元选择
 */
const TjMarketingUnit: React.FC<ITjMarketingUnitProps> = (props) => {
  const [selectShowStr, setSelectShowStr] = useState<string>('请联系管理员开通权限');
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [allMarketingUnit, setAllMarketingUnit] = useState<DataNode[]>([]);
  const [value, setValue] = useState<Key[]>([]);

  const open = () => {
    TjModal.open({
      title: <TjModalTitle title="交易单元" />,
      width: 560,
      notContentBorder: true,
      okText: '提交',
      content: (
        <SelectMarketingUnit treeData={treeData} marketingUnit={allMarketingUnit} value={value} />
      ),
      onOk: (value) => {
        return new Promise((resolve, reject) => {
          if (value && value.length > 0) {
            const stationIds = value.map((v: DataNode) => v.key);
            if (props.setTradingUnitList) {
              const arr = value?.map((v: DataNode) => v.key);
              props.setTradingUnitList(arr);
            }
            props.onChange && props.onChange(stationIds, value);
            resolve('');
          } else {
            message.warning('请至少选择一项');
            reject();
          }
        });
      },
    });
  };

  useEffect(() => {
    if (props.treeData && props.treeData.length > 0) {
      let data = props.treeData;
      if (props.marketId) {
        const item: DataNode = _.find(data, (n: DataNode) => n.key === props.marketId);
        data = item.children ? item.children : [];
      }
      const marketingUnit = getAllMarketingUnit(data);

      if (!props.value && props.defaultSelectAll) {
        setValue(marketingUnit.map((v) => v.key));
      }

      setAllMarketingUnit(marketingUnit);
      setTreeData(data);
    }
  }, [props.treeData, props.marketId]);

  useEffect(() => {
    if (props?.tradingUnitList && props.tradingUnitList?.length > 0) {
      let str = '';
      if (props.tradingUnitList?.length === allMarketingUnit.length) {
        str = '全部交易单元';
      } else {
        str = `${props.tradingUnitList?.length}/${allMarketingUnit.length}项交易单元`;
      }
      setSelectShowStr(str);
      setValue(props.tradingUnitList);
    } else {
      if (props.value && props.value.length > 0) {
        let str = '';
        if (props.value.length === allMarketingUnit.length) {
          str = '全部交易单元';
        } else {
          str = `${props.value.length}/${allMarketingUnit.length}项交易单元`;
        }
        setSelectShowStr(str);
        setValue(props.value as Key[]);
      }
    }
  }, [props.value, allMarketingUnit]);

  return (
    <div className="tj-marketing-unit">
      <Select style={{ width: '100%' }} open={false} value={selectShowStr} onClick={open} />
    </div>
  );
};

interface ITjMarketingUnitProps {
  treeData: any[];
  onChange?: (stationIds: string[], stations: any[]) => void;
  value?: Key[];
  marketId?: string;
  defaultSelectAll?: boolean;
  tradingUnitList?: any;
  setTradingUnitList?: (data: any) => void;
}

export default TjMarketingUnit;
